//
//  WZEditController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/6/30.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZEditController.h"
#import "WZDetailSchedule.h"
#import "WZRemindController.h"
#import "DateHelper.h"
#import "NSDate+CalculateDay.h"
#import "KMDatePicker.h"
#import "LocationNotification.h"

#define LocalNotification_ScheduleTitle_KEY @"scheduleTitle"
#define LocalNotification_ScheduleStartTime_KEY @"scheduleStartTime"
#define LocalNotification_ScheduleStartDate_KEY @"scheduleStartDate"

@interface WZEditController ()<UITextFieldDelegate, KMDatePickerDelegate>

@property (weak, nonatomic) IBOutlet UITableViewCell *remindView;

@property (weak, nonatomic) IBOutlet UITextField *scheduleTitleTF;

@property (weak, nonatomic) IBOutlet UITextField *dateTF;

@property (weak, nonatomic) IBOutlet UITextField *timeTF;

@property (weak, nonatomic) IBOutlet UILabel *remindLabel;

@property (weak, nonatomic) IBOutlet UISwitch *remindSW;

@property (nonatomic, assign) long long timeSec;

@property (nonatomic, assign) NSInteger badgeNumber;

@end

@implementation WZEditController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    [self setupTableView];
    
    [self layoutUI];
    
    [self loadDetailScheduleData];
}


- (void)setupTableView {
    
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xf5f5f5);
    self.navigationItem.title = @"编辑日程";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"保存" target:self sel:@selector(saveEditScheduleBtnDidClick) titleFont:Font17 titleColor:WhiteColor];
//    self.navigationItem.rightBarButtonItem.enabled = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.scheduleTitleTF.delegate = self;
    self.tableView.scrollEnabled = NO;
    self.badgeNumber = 0;
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
//    if ([_detailSchedule.alertFlag isEqualToString:@"2"]) {
//        
//        self.remindView.hidden = YES;
//    }
    
}


- (void)loadDetailScheduleData {
    
    self.scheduleTitleTF.text = self.detailSchedule.title;
    
    NSArray *timeArray = [NSDate separteTimeStr:self.detailSchedule.startTime sepStr:@" "];
    self.dateTF.text = timeArray.firstObject;
    self.timeTF.text = timeArray.lastObject;
    if ([self.detailSchedule.alertFlag isEqualToString:@"1"]) {

        self.remindSW.on = NO;
        self.remindView.hidden = YES;
        
    } else { // 提醒
        
        self.remindSW.on = YES;
        self.remindView.hidden = NO;
        self.remindLabel.text = [NSString stringWithFormat:@"提前%@%@", self.detailSchedule.beforeLength, self.detailSchedule.beforeUnitName];
    }
}


#pragma mark -- 点击cell 时控制器跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WZLog(@"section = %ld, row = %ld", indexPath.section, indexPath.row);
    
    if (2 == indexPath.section && 1 == indexPath.row) {
        
        WZRemindController *remindVC = [[WZRemindController alloc] init];
        
        remindVC.detailSchedule = self.detailSchedule;
        remindVC.block = ^(WZDetailSchedule *detailSchedule){
            
//            weakSelf.detailSchedule.alertFlag = detailSchedule.alertFlag;
//            weakSelf.detailSchedule.beforeLength = detailSchedule.beforeLength;
//            weakSelf.detailSchedule.beforeUnitName = detailSchedule.beforeUnitName;
            self.remindLabel.text = [NSString stringWithFormat:@"提前%@%@", detailSchedule.beforeLength, detailSchedule.beforeUnitName];
 
            // 刷新整个tableView
            [tableView reloadData];
            
            // 刷新指定组
//            NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:2];
//            [tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        };
        
        [self.navigationController pushViewController:remindVC animated:YES];
    }
}


- (void)layoutUI {
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect = CGRectMake(0.0, 0.0, rect.size.width, 216.0);
    
    // 年月日
    KMDatePicker *datePicker = [[KMDatePicker alloc]
                                initWithFrame:rect
                                delegate:self
                                datePickerStyle:KMDatePickerStyleYearMonthDay];
    
    self.dateTF.delegate = self;
    self.dateTF.inputView = datePicker;
    
    // 时分
    datePicker = [[KMDatePicker alloc]
                  initWithFrame:rect
                  delegate:self
                  datePickerStyle:KMDatePickerStyleHourMinute];
    
    self.timeTF.delegate = self;
    self.timeTF.inputView = datePicker;
    
    // 年月日时分；限制时间范围
    datePicker = [[KMDatePicker alloc]
                  initWithFrame:rect
                  delegate:self
                  datePickerStyle:KMDatePickerStyleYearMonthDayHourMinute];
    datePicker.minLimitedDate = [[DateHelper localeDate] addMonthAndDay:-24 days:0];
    datePicker.maxLimitedDate = [datePicker.minLimitedDate addMonthAndDay:48 days:0];
}


#pragma mark - UITextFieldDelegate
// 点击return 时收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self.view endEditing:YES];
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - KMDatePickerDelegate

- (void)datePicker:(KMDatePicker *)datePicker didSelectDate:(KMDatePickerDateModel *)datePickerDate {
    
        if (datePicker.datePickerStyle == 1) {
    
          NSString *dateStr = [NSString stringWithFormat:@"%@-%@-%@", datePickerDate.year,datePickerDate.month,datePickerDate.day];
    
            self.dateTF.text = dateStr;
       }
    
        if (datePicker.datePickerStyle == 3){
          NSString *timerStr = [NSString stringWithFormat:@"%@:%@",datePickerDate.hour,datePickerDate.minute];
            
            self.timeTF.text = timerStr;
        }
}


// 保存日程
- (void)saveEditScheduleBtnDidClick {
    
    // 发送网络请求
    NSString *str = [self.dateTF.text stringByAppendingFormat:@" %@", self.timeTF.text];
    NSString *startTime = [NSDate cTimestampStringFromString:str format:@"yyyy-MM-dd HH:mm"];
    NSString *alertFlag = self.remindSW.on ? @"2" : @"1" ;
    
    if ([alertFlag isEqualToString:@"2"]) {

        if ([self.detailSchedule.beforeUnitName isEqualToString:@"分钟"]) {
            
            self.timeSec = [self.detailSchedule.beforeLength longLongValue] * 60 * 1000;
            
        } else if ([self.detailSchedule.beforeUnitName isEqualToString:@"小时"]) {
            
            self.timeSec = [self.detailSchedule.beforeLength longLongValue] * 60 * 60 * 1000;
        } else if ([self.detailSchedule.beforeUnitName isEqualToString:@"天"]) {
            
            self.timeSec = [self.detailSchedule.beforeLength longLongValue] * 24 * 60 * 60 * 1000;
        }
    }
    
    NSString *alertTime = [NSString stringWithFormat:@"%lld", [startTime longLongValue] - self.timeSec];
    NSString *beforeLength = self.detailSchedule.beforeLength; // 30 分钟
    NSString *beforeUnitFlag = self.detailSchedule.beforeUnitFlag;
    NSString *scheduleID = self.detailSchedule.scheduleID;
    
    WZLog(@"%@", beforeLength);
    
    NSString *editFlag = @"2";
    [NetWorkShare saveScheduleWithUserName:self.oaUserName pwd:self.oaPwd scheduleID:scheduleID scheduleTitle:self.scheduleTitleTF.text startTime:startTime alertTime:alertTime alertFlag:alertFlag beforeLength:beforeLength beforeUnitFlag:beforeUnitFlag editFlag:editFlag successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                [MBProgressHUD showSuccess:@"修改日程成功"];
                
                if ([alertFlag isEqualToString:@"2"]) {
                    
                  NSArray<UILocalNotification *> *lns = [UIApplication sharedApplication].scheduledLocalNotifications;
                    for (UILocalNotification *ln in lns) {
                        NSString *scheduleTitle = [ln.userInfo objectForKey:LocalNotification_ScheduleTitle_KEY];
                        NSString *startTime = [ln.userInfo objectForKey:LocalNotification_ScheduleStartTime_KEY];
                        NSString *startDate = [ln.userInfo objectForKey:LocalNotification_ScheduleStartDate_KEY];
                        if ([scheduleTitle isEqualToString:self.scheduleTitleTF.text] && [startTime isEqualToString:_timeTF.text] && [startDate isEqualToString:_dateTF.text]) {
                            
                            [[UIApplication sharedApplication] cancelLocalNotification:ln];
                            
                            // TODO :根据标示删掉
//                            [LocationNotification cancelLocalNotificationWithIdentifier:ln];
                            
                            NSTimeInterval localNotifyTime = ([startTime longLongValue] - self.timeSec) / 1000;
                            NSDate *fireDate = [NSDate dateWithTimeIntervalSince1970:localNotifyTime];
                            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                            [dict setObject:_timeTF.text forKey:LocalNotification_ScheduleStartTime_KEY];
                            [dict setObject:_dateTF.text forKey:LocalNotification_ScheduleStartDate_KEY];
                            [dict setObject:_scheduleTitleTF.text forKey:LocalNotification_ScheduleTitle_KEY];
                            [LocationNotification registerLocalNotificationWithFireDate:fireDate repeatType:0 entity:dict.copy];
                            break;
                        }
                    }
                }
                
                // 修改数据模型
//                self.detailSchedule.title = self.title;
//                self.detailSchedule.startTime = startTime;
//                self.detailSchedule.alertFlag = alertFlag;
                
                if (_block) {
                    _block();
                }
                
                // 跳转
                [self.navigationController popViewControllerAnimated:YES];
                
//                self.saveScheduleID = responseObject[@"id"];
            } else {
                
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
        } else {
            [MBProgressHUD showError:UNKNOWNERROR];
        }
        
        WZLog(@"%@", self.scheduleTitleTF.text);
        WZLog(@"result = %@", responseObject);
        //        WZLog(@"保存成功");
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"error = %@", error);
    }];
}


- (IBAction)remindSwitch:(UISwitch *)sender {
    
    if (!sender.isOn) {
        
        self.remindView.hidden = YES;
        
    } else {
        
        self.remindView.hidden = NO;
    }
}

@end
